#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2024/4/7 15:08
# @Author  : 王凯
# @File    : pdd_login.py
# @Project : scrapy_spider
import json

import requests
from loguru import logger

from apps.pdd.pdd.utils.js import gen_anti_content
from apps.pdd.pdd.utils.pdd_verify import PddSliderVerify

MSG_MAP = {
    "1101": "网络繁忙，请稍后再试",
    "30400": "没有安装QQ客户端",
    "40000": "错误的请求地址或方法",
    "40001": "登录已过期，请重新登录",
    "40002": "网络繁忙，请稍后再试",
    "40003": "错误的请求参数",
    "40004": "微信登录失败",
    "40005": "请求还在处理中",
    "40006": "手机登录验证码错误",
    "40015": "验证码重复请求",
    "40016": "验证码超出当天限制",
    "40017": "今日可发送次数已达上限",
    "40018": "验证码填写错误",
    "40019": "验证码填写超时",
    "40020": "登录失败",
    "40031": "微信登录失败!",
    "40032": "QQ登录失败!",
    "40033": "登录重试失败，请稍后再试",
    "48001": "图片格式错误",
    "48002": "图片大小超过限制",
    "50000": "当前访问人数较多，请稍后再试",
    "54001": "该账户需要安全验证",
    "54003": "该账户安全验证未通过，暂时无法登录",
    "60005": "用户拒绝",
    "60006": "用户取消",
    "60100": "未安装微信客户端",
    "60110": "未安装微博客户端",
    "60120": "未安装手机QQ",
}


class PddMobileLogin:
    session = requests.Session()
    session.headers = {
        "Host": "mobile.pinduoduo.com",
        "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1",
        "Cache-Control": "no-cache",
    }

    def __init__(self, cookie=None):
        if cookie:
            self.session.cookies.update(cookie)
        self.init()

    def init(self):
        url = "http://mobile.pinduoduo.com/"
        self.session.get(url)

    def get_server_time(self):
        url = "https://mobile.pinduoduo.com/proxy/api/api/server/_stm?pdduid=0"
        data = self.session.get(url).json()
        return data["server_time"]

    def send_sms_code(self, mobile="18888888888"):
        return_data = {"code": 400, "msg": "验证码发送失败", "error_code": None, "error_message": None, "verify_auth_token": None, "mobile": mobile}
        anti_content = gen_anti_content()
        url = "https://mobile.pinduoduo.com/proxy/api/api/sigerus/mobile/code/request?pdduid=0"
        headers = {**self.session.headers, "Content-Type": "application/json;charset=UTF-8", }
        data = {
            "platform": "4",
            "fingerprint": json.dumps(
                {
                    "innerHeight": 812,
                    "innerWidth": 375,
                    "devicePixelRatio": 3,
                    "availHeight": 812,
                    "availWidth": 375,
                    "height": 812,
                    "width": 375,
                    "colorDepth": 24,
                    "locationHerf": "https://mobile.pinduoduo.com/login.html",
                    "referer": "login",
                    "timezoneOffset": -480,
                    "navigator": {
                        "appCodeName": "Mozilla",
                        "appName": "Netscape",
                        "hardwareConcurrency": 16,
                        "language": "zh-CN",
                        "cookieEnabled": True,
                        "platform": "iPhone",
                        "doNotTrack": "unspecified",
                        "ua": self.session.headers.get("User-Agent"),
                        "vendor": "",
                        "product": "Gecko",
                        "productSub": "20100101",
                    },
                },
                ensure_ascii=False,
                separators=(",", ":"),
            ),
            "touchevent": "{}",
            "mobile": mobile,
            "anti_content": anti_content,
        }
        resp = self.session.post(url, data=json.dumps(data, separators=(",", ":")), headers=headers)
        result = resp.json()
        logger.debug(f"发送验证码结果: {mobile} {result}")
        if result == {}:
            return_data = {"code": 200, "msg": "验证码发送成功", "error_code": None, "error_message": None, "verify_auth_token": None, "mobile": mobile}
        else:
            return_data = {
                "code": 201, "msg": "验证码发送异常", "error_code": result.get("error_code"), "error_message": MSG_MAP.get(str(result.get("error_code")), ""),
                "verify_auth_token": result.get("verify_auth_token"), "mobile": mobile
            }
        return return_data

    def verify_sms_code(self, mobile="18888888888", sms_code="123456"):
        """
        验证手机验证码
        {'_nano_fp': 'XpmaX5dyn5CJlpTqXo_Q5ij5GIQHsZYq4tFOzu3a', 'api_uid': 'CiTeiGYTi0WYaQBWC1sRAg==', 'PDDAccessToken': 'FWPIZ52ZHSSVDHVNJN2FD4O7YH72KLBROB2G6HOR2PJMV4BI5UXA1206a3a', 'acid': 'c2773fb181f75c74b9dda0e2db9dfeba'}
        正常：{'uid': 9847140310122, 'uin': 'ROGZA7R7XPMXA2IO5ES2IDNAUU_GEXDA', 'access_token': 'FWPIZ52ZHSSVDHVNJN2FD4O7YH72KLBROB2G6HOR2PJMV4BI5UXA1206a3a', 'acid': 'c2773fb181f75c74b9dda0e2db9dfeba', 'mobile_id': '7173939602209382400861', 'mobile_des': '189****1861', 'complete_newer': False}
        :param mobile:
        :param sms_code:
        :return:
        """
        return_data = {"code": 400, "msg": "验证码验证失败", "error_code": None, "error_message": None, "verify_auth_token": None, "mobile": mobile}
        anti_content = gen_anti_content()
        # self.session.cookies.set("_nano_fp", anti_content_dict["_nano_fp"])
        url = "https://mobile.pinduoduo.com/proxy/api/api/sigerus/login_mobile?pdduid=0"
        data = {
            "mobile": mobile,
            "code": sms_code,
            "anti_content": anti_content,
            "add_cookie": True,
            "login_app_id": 155,
        }
        headers = {**self.session.headers, "Content-Type": "application/json;charset=UTF-8", }
        resp = self.session.post(url, data=json.dumps(data, separators=(",", ":")), headers=headers)
        result = resp.json()
        logger.debug(f"校验验证码结果: {mobile} {sms_code} {result}")
        session_cookies = self.session.cookies.get_dict()
        verify_success_cookies = {
            "api_uid": session_cookies.get("api_uid"),
            "_nano_fp": session_cookies.get("_nano_fp"),
            "PDDAccessToken": result.get("access_token"),
            "pdd_user_id": str(result.get("uid")),
            "pdd_user_uin": result.get("uin"),
            "pdd_vds": session_cookies.get("pdd_vds"),
        }
        self.session.cookies.update(verify_success_cookies)
        if result.get("success") is False:
            return_data = {
                "code": 201,
                "msg": "验证码验证异常",
                "error_code": result.get("error_code"),
                "error_message": MSG_MAP.get(result.get("error_code"), 0),
                "mobile": mobile,
                "sms_code": sms_code,
                "cookies": None,
            }
        else:
            return_data = {
                "code": 200,
                "msg": "验证码验证成功",
                "error_code": None,
                "error_message": None,
                "mobile": mobile,
                "sms_code": sms_code,
                "cookies": verify_success_cookies,
            }
        logger.info(return_data)
        return return_data

    def personal_check(self):
        pdd_user_id = self.session.cookies.get_dict().get("pdd_user_id")
        url = f"https://mobile.pinduoduo.com/proxy/api/api/barrow/query?pdduid={pdd_user_id}&page_sn=10001&offset=0&count=20&list_id=rec_list_personal_fmcq14&app_name=personal"
        response = self.session.get(url, verify=False)
        if response.status_code == 200:
            result = response.json()
            if result.get("success") is True:
                logger.success(f"个人主页请求成功 {pdd_user_id} status_code: {response.status_code}")
                return True
            else:
                logger.error(f"个人主页请求失败 {pdd_user_id} response: {result}")
                if result.get("error_code") == 54001:
                    cookie = PddSliderVerify(result.get("verify_auth_token")).run()
                return False
        else:
            logger.error(f"个人主页请求失败 {pdd_user_id} status_code: {response.status_code} response: {response.text}")
            return False

    def run(self, mobile="18888888888"):
        send_result = self.send_sms_code(mobile)
        if send_result["code"] == 200:
            logger.success(f"发送验证码成功 {mobile}")
        else:
            for _ in range(3):
                logger.error(f"发送验证码失败 {mobile} {send_result}")
                verify_auth_token = send_result['verify_auth_token']
                verify_result = PddSliderVerify(verify_auth_token).run()
                if verify_result:
                    send_result = self.send_sms_code(mobile)
                    if send_result["code"] == 200:
                        logger.success(f"发送验证码成功 {mobile}")
                        break
                else:
                    continue
            else:
                logger.error(f"发送验证码失败 {mobile} {send_result}")
                return
        result = self.verify_sms_code(mobile, input("请输入短信验证码:"))
        if self.personal_check():
            return result


if __name__ == "__main__":
    ck = {
        # "jrpl": "da0ZRy31tlibeDCIdGJhw6aqYjCQA3uG",
        # "njrpl": "da0ZRy31tlibeDCIdGJhw6aqYjCQA3uG",
        # "dilx": "bgu0VlRF3qSGzv~K2lU_V",
        # "api_uid": "Ci1IFGYTo1ie7wBcBBSDAg==",
        # "PDDAccessToken": "LX6P3GASNGFVQELFT2PMZ2YENA2HXARSF6NIY6KVEJSWSUP3M77A121c274",
        # "pdd_user_id": "1576526274",
        # "pdd_user_uin": "YD7VU6OJE2DG3NSYML6ZPXB5DE_GEXDA",
        # "_nano_fp": "XpmaX5djXq9yXqTyXC_YEuAa4PYEmwhTdHNRpgBX",
        # "webp": "1",
        # "arp_scroll_position": "0",
        # "pdd_vds": "gaBTesndxTdemnIIbBenNnGbddNxOmBGwTswnmuxwTBumbBxwLOwlsLmLBbB",
        # "rec_list_personal": "rec_list_personal_i701jh"

        # 'api_uid': 'CiDatGYXsf0gdQBhKgYRAg==',
        # '_nano_fp': 'XpmaX5Cxl0UqnqTjXT_wA9uxpjnCiHD3M5BpJkSa',
        # 'PDDAccessToken': 'MKRC5JLTP6CNXJ2NNS6UDLE7NWKR4ZWXGJFQHAQ2WJBUXVGIATBA121c274',
        # 'pdd_user_id': '1576526274',
        # 'pdd_user_uin': 'YD7VU6OJE2DG3NSYML6ZPXB5DE_GEXDA',
        # 'pdd_vds': 'gapLqOBGvNhaumqOeoeLrNdGqafLhIftrnfEpnqLpoZPTirLByuIvPDQvPZL',

        # 'api_uid': 'CiZuSGauOoAfEQBTE026Ag==',
        # '_nano_fp': None,
        # 'PDDAccessToken': 'PUTY6PWDEWZD4MC2A2CR647BKMSHTV3P57C7CZLZ5FG33AX7KGIQ121c274',
        # 'pdd_user_id': '1576526274',
        # 'pdd_user_uin': 'YD7VU6OJE2DG3NSYML6ZPXB5DE_GEXDA',
        # 'pdd_vds': None

    }
    # mobie = "15670813638"
    # mobie = "18924021861"
    mobie = "18888888888"
    # mobie = "18889159571"
    # mobie = "13738349304"
    test = PddMobileLogin(ck)
    cookies_dict = test.run(mobie)
    # test.personal_check()
